package org.wlw.user;

import java.util.ArrayList;
import java.util.List;

public class UserManager {
	private List<User> users;
	
	public UserManager() {
		users = new ArrayList<User>();
	}
	
	public User load(String username) {
		for(User u:users) {
			if(username.equals(u.getUsername())) 
				return u;
		}
		return null;
	}
	
	public void list() {
		System.out.println("\t用户名\t\t用户昵称\t\t年龄\t\t密码");
		System.out.println("**********************************************************************************");
		for(User u:users) {
			System.out.println(u);
		}
	}
	
	public void add(int pos,User user) {
		if(user.getPassword().length()<=2) {
			throw new UserException("密码太短!");
		}
		User tu = load(user.getUsername());
		if(tu!=null) {
			throw new UserException("用户名已经存在！不能添加");
		}
		users.add(pos, user);
	}
	
	public void add(User user) {
		add(users.size(),user);
	}
	
	public void delete(String username) {
		User tu = load(username);
		if(tu==null) {
			throw new UserException("删除的用户不存在!");
		}
		users.remove(tu);
	}
	
	public void update(User user) {
		User tu = this.load(user.getUsername());
		if(tu==null) {
			throw new UserException("更新的用户不存在!");
		}
		tu.setAge(user.getAge());
		tu.setNickname(user.getNickname());
		tu.setPassword(user.getPassword());
	}
	
	public User login(String username,String password) {
		User tu = this.load(username);
		if(tu==null) {
			throw new UserException("用户不存在！");
		}
		if(!tu.getPassword().equals(password)) {
			throw new UserException("密码不正确!");
		}
		return tu;
	}
}
